<template>
    <view class="cart-temp" :style="themeColor">
        <view class="topsack">
            <scroll-view :scroll-x="true" class="topsackbg" scroll-with-animation :show-scrollbar="false">
                <view class="sacklist">
                    <view v-for="item in shoppingBag">
                        <image src="../../static/sack.png"></image>
                        <text class="name">{{ item.ProductName }}{{ item.AttributeNameValue }}</text>
                        <text class="name">¥{{ item.Price }}</text>
                        <view class="input-number-box">
                            <button class="number-btn number-btn-minus" @click="addBag(item, -1)"></button>
                            <view class="btn-input-box">
                                <input v-model="item.CarNumber" type="number" @blur="addBag(item, 0)" />
                            </view>
                            <button class="number-btn number-btn-plus" @click="addBag(item, 1)"></button>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
        <view class="main">
            <mescroll-uni
                v-if="isLoadOk"
                :height="height"
                ref="mescrollRef"
                @init="mescrollInit"
                :down="downOption"
                @down="refresh"
                :up="upOption"
                @up="getData">
                <view class="header-action-bar header-action-bar-title" @click="isEdit = !isEdit">
                    <text class="car-title">已选商品</text>
                    <text>{{ isEdit ? "完成" : "编辑" }}</text>
                </view>
                <view class="cart-list">
                    <cart-item
                        v-for="(item, index) in datas"
                        :isShowCheckBox="isEdit"
                        :key="item.ProductId"
                        :selectData="selectData"
                        :productInfo="item"
                        @upNum="upNum"
                        @changeCheck="changeCheck"
                        @checkboxChange="checkboxChange"
                        @delTip="delTip"
                        >{{ item.name }}</cart-item
                    >
                </view>
            </mescroll-uni>
        </view>

        <cart-bottom-bar
            ref="cartBottomBar"
            :isHome="isHome"
            :isEdit="isEdit"
            :selectData="selectData"
            :shoppingBagids="shoppingBagids"
            :isShowSelect="isShowSelect"
            :shopingPrice="shopingPrice"
            :productInfo="datas"
            @scan="scan"
            @selectAll="selectAll"
            @delCart="delCart"
            @isSelectAllBack="isSelectAllBack"></cart-bottom-bar>

        <uni-popup ref="delTip" type="dialog">
            <uni-popup-dialog
                type="text"
                title="温馨提示"
                content="确定删除该商品?"
                :before-close="true"
                @close="close"
                @confirm="doDel"></uni-popup-dialog>
        </uni-popup>
    </view>
</template>

<script>
import cartItem from "@/pages_scan/components/cart/cart-item.vue"
import cartBottomBar from "@/pages_scan/components/cart/cart-bottom-bar.vue"

import { getUserCarList, deleteUserCar, updateCart } from "@/utils/cartUtil.js"
import { getElementHeight } from "@/uni-sub-base/utils/elementUtil.js"
import { eventBus } from "@/utils/eventBus.js"
import { GetScanAddBuyProducts, AddScanBuyProductToCar } from "@/service/api/product.js"
export default {
    components: {
        cartItem,
        cartBottomBar,
    },
    props: {
        isHome: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            amount: 1,
            isEdit: false,
            isShowSelect: true,
            downOption: {
                use: true,
            },
            upOption: {},
            datas: [],
            isLoadOk: false,
            height: "",
            isEmpty: false,
            selectData: {
                proIds: [],
                ids: [],
            },
            isSelectAll: true,
            delPro: null,
            config: {
                title: "购物车",
                back: false,
                centerSlot: true,
                barPlaceholder: true,
                rightSlot: false,
                rightBtns: [
                    {
                        id: 1,
                        btnType: 1,
                        type: "编辑",
                    },
                ],
            },
            shoppingBag: [],
            shoppingBagids: [],
            shopingPrice: 0,
        }
    },
    created() {
        this.config.back = true
        this.$nextTick(() => {
            this.getListHeight()
        })
    },
    mounted() {
        eventBus.$on("SET_CART", (msg) => {
            if (msg) {
                this.datas = msg
            }

            //购物车数据变化 更新UI
            this.upView()
            this.upBottom()
            if (this.isSelectAll) {
                this.selectAll(true)
            }
        })
        this.bag()
    },
    methods: {
        //获取列表高度
        getListHeight() {
            //获取商品高度
            getElementHeight(this, ".main", (e) => {
                e = e - 120 - uni.upx2px(150)
                this.height = e + "px"
                this.isLoadOk = true
                this.$nextTick(() => {
                    this.refresh()
                })
            })
        },
        bag() {
            GetScanAddBuyProducts().then((res) => {
                if (res.State == 1) {
                    this.shoppingBag = res.Data
                    this.getshoppingBagids()
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        addBag(item, type) {
            item.CarNumber = parseInt(Number(item.CarNumber))
            if (type == 0) {
                if (item.CarNumber < 0) {
                    item.CarNumber = 0
                }
            } else {
                item.CarNumber = item.CarNumber + type
            }
            if (item.CarNumber < 0) {
                item.CarNumber = 0
            }
            this.$forceUpdate()
            let obj = {
                ProductId: item.ProductId,
                Amount: item.CarNumber,
                UnitId: item.UnitId,
                UnitName: item.UnitName,
                skuId: item.SkuId,
                ratio: item.Ratio || 1,
            }
            let param = []
            param.push(obj)
            updateCart(param, false, true, false, 5).then((res) => {
                this.$forceUpdate()
                this.bag()
                // this.$emit("upNum", this.productInfo)
            })
        },
        getshoppingBagids() {
            let ids = []
            let price = 0
            this.shoppingBag.forEach((pro) => {
                if (pro.CarNumber > 0) {
                    ids.push(pro.CarIds)
                    price = price + pro.Price * pro.CarNumber
                }
            })
            this.shoppingBagids = ids
            this.shopingPrice = price
        },
        //获取数据
        getData() {
            getUserCarList(true, false, 5).then((res) => {
                this.datas = res
                if (res.length > 0) {
                    this.mescroll.endBySize(res.length, 1)
                } else {
                    this.isEmpty = true
                    this.mescroll.endBySize(0, 0)
                }
                this.upBottom()
                setTimeout(() => {
                    this.selectAll(true)
                }, 500)
            })
        },
        //更新UI
        upView() {
            if (this.mescroll) {
                this.mescroll.endBySize(this.datas.length, 1)
            }
        },
        //更新底栏
        upBottom() {
            if (this.$refs.cartBottomBar) {
                this.$refs.cartBottomBar.getTotal(this.datas)
            }
        },
        //刷新
        refresh() {
            this.mescroll.resetUpScroll()
        },
        //更新底栏数据
        upNum(e) {
            this.upBottom()
        },
        //去采购
        emptyClick() {
            this.easyGoProduct()
        },
        //删除
        delCart(isClearAll) {
            if (isClearAll) {
                let ids = []
                this.datas.forEach((pro) => {
                    pro.SubItems.forEach((sub) => {
                        ids.push(String(sub.ID))
                    })
                })
                let param = {
                    ids: ids.join(","),
                }
                this.doDelCart(param)
            } else if (this.selectData.ids.length > 0) {
                let param = {
                    ids: this.selectData.ids.join(","),
                }
                this.doDelCart(param)
            }
        },
        //删除接口
        doDelCart(param) {
            uni.showLoading({
                title: "提交中",
            })
            deleteUserCar(param, false, 5).then((res) => {
                if (res) {
                    uni.hideLoading()
                    // this.refresh()
                    this.isEdit = false
                    this.setBtnText()
                    this.selectData.ids = []
                }
            })
        },
        //全选
        selectAll(e) {
            // this.isSelectAll = e
            let ids = []
            if (e) {
                this.datas.forEach((pro) => {
                    pro.SubItems.forEach((sub) => {
                        ids.push(String(sub.ID))
                    })
                })
            }
            this.setTreeSelect(ids)
        },
        //商品子项选择回调
        checkboxChange(e, id) {
            let values = e.detail.value
            if (values.length > 0) {
                this.selectData.ids.push(values[0])
            } else {
                this.selectData.ids.forEach((e, index) => {
                    if (e == id) {
                        this.selectData.ids.splice(index, 1)
                    }
                })
            }
            this.setTreeSelect(this.selectData.ids)
        },
        //数据处理
        setTreeSelect(ids) {
            //去重
            const set = new Set(ids)
            ids = [...set]
            this.selectData = {
                ids: ids,
            }
            this.$forceUpdate()
        },
        //单个商品全选or取消全选
        changeCheck(obj) {
            let isSelect = obj.isSelect
            let proId = obj.proId
            let subIds = obj.subIds
            if (isSelect) {
                //全选
                this.datas.forEach((e) => {
                    if (e.ProductId == proId) {
                        e.SubItems.forEach((sub) => {
                            this.selectData.ids.push(String(sub.ID))
                        })
                    }
                })
            } else {
                //取消全选
                for (var i = this.selectData.ids.length - 1; i >= 0; i--) {
                    let e = this.selectData.ids[i]
                    subIds.forEach((sub) => {
                        if (e == sub) {
                            this.selectData.ids.splice(i, 1)
                        }
                    })
                }
            }
            this.setTreeSelect(this.selectData.ids)
        },
        isSelectAllBack(e) {
            this.isSelectAll = e
        },
        close() {
            this.$refs.delTip.close()
        },
        doDel() {
            let obj = {
                ProductId: this.delPro.ProductId,
                Amount: 0,
                UnitId: this.delPro.UnitId,
                UnitName: this.delPro.DefaultUnit,
                skuId: this.delPro.SkuId,
                ratio: this.delPro.Ratio,
            }
            let param = []
            param.push(obj)
            updateCart(param, false, true, false, 5).then((res) => {})
            this.close()
        },
        delTip(e) {
            this.delPro = e
            this.$refs.delTip.open()
        },
        rightClick(e) {
            if (e.id == 1) {
                this.isEdit = !this.isEdit
                this.setBtnText()
            }
        },
        setBtnText() {
            this.config.rightBtns[0].type = this.isEdit ? "完成" : "编辑"
        },
        scan(result) {
            let path = "?SearchKey=" + result
            AddScanBuyProductToCar(path).then((res) => {
                if (res.State == 1) {
                    this.getData()
                    this.bag()
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
    },
}
</script>

<style lang="scss" scoped>
page {
    background: #f7f7f7;
}
.container {
    // .bottom-bar {
    // 	/* #ifdef H5 */
    // 	bottom: 50px;
    // 	/* #endif */
    // }

    // .bottom-bar-mark {
    // 	/* #ifdef H5 */
    // 	height: 0;
    // 	/* #endif */
    // }
}

.cart-temp {
    // display: flex;
    // flex-direction: column;
}

.cart-list {
    padding: 0 $app-page-padding $app-page-padding $app-page-padding;
}

.car-title {
    font-weight: bold;
    font-size: 32rpx;
    color: $color-gray-1;
}
.input-number-box {
    .btn-input-box {
        display: block;
        text-align: center;
        font-size: $font-size-26;
        height: auto;
        width: 64rpx;
    }
    .number-btn {
        display: flex;
        justify-content: center;
        border: none;
        background-color: none;
        justify-content: center;
        align-items: center;
        position: relative;
        font-size: 45rpx;
        line-height: 56rpx;
        height: 56rpx;
        width: 56rpx;
        text-align: center;
        overflow: hidden;
        border-radius: 100rpx;
        display: block;
        background-repeat: no-repeat;
        background-size: 100%;
        background-position: center;

        &:before {
            border: none;
        }

        &:after {
            border: none;
        }
    }

    .number-btn-minus {
        background-image: url(@/static/icon/icon_btn_minus.png);
    }

    .number-btn-plus {
        background-image: url(@/static/icon/icon_btn_plus.png);
    }
}
.topsack {
    padding: 24rpx;
}
.topsackbg {
    background: #fff;
    border-radius: 16rpx;
}
.sacklist {
    // margin: 24rpx;
    padding: 24rpx 12rpx;
    display: flex;
    justify-content: flex-start;
    border-radius: 16rpx;
    & > view {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        white-space: nowrap;
        margin: 0 14rpx;
        image {
            width: 72rpx;
            height: 72rpx;
            margin: 8rpx 0 16rpx 0;
        }
        .name {
            font-size: 28rpx;
            margin-bottom: 12rpx;
        }
    }
}
.cart-main {
    // padding: 24rpx;
}
.header-action-bar {
    margin: 0 24rpx;
    border-radius: 16rpx 6rpx 0 0;
}
.mescroll-upwarp {
    padding: 0 !important;
}
</style>
